import { DomUtils } from '../utils/DomUtils';

/**
 * 必应(https://cn.bing.com/*)网页优化
 */

export class Bing {

    static hostname = 'cn.bing.com';

    main(pathname) {
        if (pathname === '/') {
            // 首页
            this.handleHome();
        } else if (pathname === '/search') {
            // 搜索页面
            this.handleSearch();

            // 监听页面变化，当页面变化时重新处理
            DomUtils.observe(document.body, ['childList'], { childList: true }, () => {
                const result = document.querySelector('#b_results');
                if (result && result.style.width !== '1000px') {
                    this.handleSearch();
                }
            });
        }
    }

    /**
    * Bing首页优化
    */
    handleHome() {
        DomUtils.setCss('html', { overflow: 'auto' });
        DomUtils.intervalRemove([
            // 下载Edge APP的二维码
            '#id_qrcode',
        ]);

        this.removeMSNNews();
        document.querySelector('#sb_form_q').addEventListener('focus', () => {
            console.log('focus');
            removeMSNNews();
        });
    }

    /**
     * Bing搜索页面优化
     */
    handleSearch() {
        DomUtils.hide([
            '#b_pole',
            '#b_context',
            '#b_footer',
            '.b_phead_sh_link',
            '.b_rs',
            '#b_mrs_DynamicMRS',
            ...document.querySelectorAll('#b_content > aside')
        ]);
        DomUtils.setCss('#b_content', {
            display: 'flex',
            'align-items': 'center',
            'justify-content': 'center',
            'padding-left': 0
        });
        DomUtils.setCss('#b_results', { width: '1000px' });
        DomUtils.setCss('#sb_form_q', { width: '840px' });
        DomUtils.setCss('header', { paddingLeft: '16vw' });
    }

    /**
     * 移除Bing首页的MSN新闻(需要多次移除)
     */
    removeMSNNews() {
        const parent = document.querySelector('#scroll_cont');
        parent.querySelector('#vs_cont')?.remove();
        DomUtils.observe(parent, ['childList'], { childList: true }, ({ observer, mutationsList, index }) => {
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    parent.querySelector('#vs_cont').remove();
                    index++;
                    if (index >= 3) {
                        observer.disconnect();
                    }
                }
            }
        });
    }
}